// 是否线上坏境
var isOnline = true;
// 公共接口
var baseUrl = isOnline ? "https://app.ameimeika.com" : "https://mp.ameimeika.com"
var pageUrl = 'https://h5.ameimeika.com/Fortunebag/index.html';
var imgUrl = "https://img.ameimeika.com/"; // 图片接口域名
var noshare = false;
var model = 0;
var type = 0;
var env = '';
var token = '';
var isBottom = false;
var page = 1; // 每页显示条数
var pageSize = 10; // 每页展示条数
var keyword = '全积分兑换';
var sales_sort = 1; // 销售(默认高到低)
var collect_sort = 0; // 人气
var price_sort = 0; // 价格
var goodslist = []; // 是否在页面最下面
var number = ''
noshare = GetPar('noshare');
model = GetPar('model');
type = GetPar('type');
if ((noshare == 'true' && env != 1) || (type == '2' && model == '2' && env != 1) || (type == '2' && model == '3' && env != 1)) {
    token = '';
    console.log(8888, '不是微信环境')
} else {
    token = GetPar('user_token');
}
getEnv()
tongji('view')
isDown({
    callback: function () {
        page++;
        getGoods();
    }
});
// 获取token
function getToken() {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
    var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    window['getToken'] = function (result) {
        var res = JSON.parse(result)
        token = res.token;
    }
    if (isAndroid) {
        window.WebViewJsController.jsGetData(1, 1, null, 'getToken')
    }
    if (isIOS) {
        window.webkit.messageHandlers.token.postMessage({})
    }
}
setTimeout(() => {
    http();
}, 500);
console.log(token)

function http() {
    var ua = navigator.userAgent.toLowerCase();
    if (token) {
        ajax('/api/act/new_year/status', {}, function success(res) {
            console.log(res)
            if (res.status_code == 0) {
                if (res.data[0].status == 0) {
                    $('#getBtn').click(function () {
                        $('html,body').animate({
                            scrollTop: $('.double').offset().top
                        }, 800);
                    })
                    $('#btn').click(function () {
                        var name = $('#name').val();
                        var mobile = $('#phone').val();
                        if (name === "") {
                            showMsg('请输入您想变美的部位');
                        } else if (mobile === "") {
                            showMsg('请输入您的手机号');
                        } else {
                            $('html,body').animate({
                                scrollTop: $('.active').offset().top
                            }, 800);
                            ajax('/api/act/new_year/one_step', {
                                mobile: mobile,
                                beautify: name,
                            }, function success(res) {
                                if (res.status_code == 0) {
                                    $('.active-box .right img').attr('src', 'https://img.ameimeika.com/h5_images/fortunebag/yilingqu.png');
                                    $("#getBtn").unbind("click")
                                    var numberIndex = 1;
                                    getFu(numberIndex)
                                }
                            });
                        }
                    })
                }
                if (res.data[0].status == 1) {
                    var name = res.data[0].beautify;
                    var phone = res.data[0].mobile;
                    console.log(name, phone)
                    $('.name').html('<input type="text" id="name" disabled="disabled">')
                    $('#name').val(name)
                    $('.phone').html('<input type="tel" id="phone" disabled="disabled" >' + '<button id="btn">' + '</button>')
                    $('#phone').val(phone)
                    $('.active-box .right img').attr('src', 'https://img.ameimeika.com/h5_images/fortunebag/yilingqu.png');
                    $('#btn').click(function () {
                        $('html,body').animate({
                            scrollTop: $('.active').offset().top
                        }, 800);
                    })
                    $("#getBtn").unbind("click")
                }
                if (res.data[3].browse_number == 5 && res.data[3].status == 1) {
                    $('#getDai img').attr('src', 'https://img.ameimeika.com/h5_images/fortunebag/yilingqu.png');
                    $("#getDai").unbind("click")
                }
                if (res.data[3].browse_number > 0) {
                    number = res.data[3].browse_number;
                    $('.Dcontent').html("(" + number + "/" + "5" + ")")
                }
                if (res.data[2].status == 1) {
                    $('#getFuzifu img').attr('src', 'https://img.ameimeika.com/h5_images/fortunebag/yilingqu.png');
                    $("#getFuzifu").unbind("click")
                }
                if (res.data[1].share_number > 0) {
                    numberTwo = res.data[1].share_number;
                    $('.kaContent').html("(" + numberTwo + "/" + "3" + ")")
                }
                if (res.data[1].share_number == 3 && res.data[1].status == 1) {
                    $('#getKazifu img').attr('src', 'https://img.ameimeika.com/h5_images/fortunebag/yilingqu.png');
                    $("#getKazifu").unbind("click")
                }
            } else if (res.status_code == 1009) {
                console.log('跳转到登录页面')
                if (ua.match(/MicroMessenger/i) == "micromessenger") {
                    wx.miniProgram.navigateTo({
                        url: "/pages/login/main"
                    });
                } else if (env == 2) {
                    window.WebViewJsController.jsGetData(1, 1, null, null)
                } else if (env == 3) {
                    window.webkit.messageHandlers.token.postMessage(obj)
                }
            }
        })
    } else if (!token && ua.match(/MicroMessenger/i) == "micromessenger") {
        setTimeout(() => {
            wx.miniProgram.navigateTo({
                url: "/pages/login/main"
            });
        }, 500)
    } else if (!token && env == 2) {
        window.WebViewJsController.jsGetData(1, 1, null, null)
    } else if (!token && env == 3) {
        var obj = {}
        window.webkit.messageHandlers.token.postMessage(obj)
    }
}
var hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' : null;
console.log(hiddenProperty);
document.addEventListener('visibilitychange', () => {
    if (document[hiddenProperty]) {} else {
        //当从原生页面用户一系列操作后,返回H5的时候,这里会被触发
        http()
        getToken()
    }
});

// ajax('/api/v4_2/user/login', {
//     username: 13067526808,
//     mode: 2,
//     password: 'a123456'
// }, function success(res) {
//     token = res.data.token;
//     http();
// })

//传入参数名称 获取参数（为字符串形式）
function GetPar(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}
$(function () {
    var ua = navigator.userAgent.toLowerCase();
    $('#getDai').click(function () {
        $('html,body').animate({
            scrollTop: $('.projectList').offset().top
        }, 800);
    })
    // 规则弹框
    $('.addRule').click(function () {
        tongji('rule_click')
        $("#ruleBox").removeClass('hide');
        document.body.addEventListener('touchmove', function (e) {
            if (scrollmark == 1) {
                e.preventDefault();
            } else {
                return false;
            }
        }, {
            passive: false
        }); //passive处理兼容
    })
    $('.close').click(function () {
        $("#ruleBox").addClass('hide');
    })
    // 商品流筛选
    $(".filter-item").click(function () {
        var tag = $(this).data('type');
        $(this).addClass('red').siblings('.filter-item').removeClass('red');
        $(this).children().attr('src', 'https://img.ameimeika.com/h5_images/doublDenier/mainVenue/xia-hong.png');
        $(this).siblings().children().attr('src', 'https://img.ameimeika.com/h5_images/doublDenier/mainVenue/row.png');
        if (tag == 1) { // 销量
            goodslist = []
            isBottom = false;
            collect_sort = "";
            page = 1;
            price_sort = "";
            sales_sort = 1
            getGoods();

        } else if (tag == 2) { // 人气
            goodslist = []
            isBottom = false;
            sales_sort = "";
            price_sort = "";
            collect_sort = 1;
            page = 1;
            getGoods();
        } else if (tag == 3) { // 价格
            isBottom = false;
            goodslist = []
            sales_sort = "";
            price_sort = 1;
            sales_sort = "";
            page = 1;
            getGoods();
        }
        var h = window.screen.height
        $("#maillList").html("").height(h)
        var h = window.screen.height
        $("#maillList").html("")
        $("html,body").animate({
            scrollTop: $("#maillList").offset().top - 32
        });
    })
    $('#plushide').click(function () {
        $('#plusBox').addClass('hide')
    });
    if (!token && ua.match(/MicroMessenger/i) == "micromessenger") {
        $('#double').click(function () {
            setTimeout(() => {
                wx.miniProgram.navigateTo({
                    url: "/pages/login/main"
                });
            }, 500)
        })
    }
    if (!token) {
        $('#double').click(function () {
            if ((noshare == 'true' && env != 1) || (type == '2' && model == '2' && env != 1) || (type == '2' && model == '3' && env != 1)) {
                window.location.href = 'http://url.cn/5TKxNtL'
                return
            }
        })

    }
})
// 查询袋字福领取
function getFu(numberIndex) {
    ajax('/api/act/new_year/status', {}, function success(res) {
        if (numberIndex === 4) {
            if (res.data[3].browse_number > 0 && res.data[3].browse_number <= 5) {
                number = res.data[3].browse_number;
                $('.Dcontent').html("(" + number + "/" + "5" + ")")
            }
            if (res.data[3].status == 1) {
                $('#getDai img').attr('src', 'https://img.ameimeika.com/h5_images/fortunebag/yilingqu.png');
                $("#getDai").unbind("click")
            }
        } else if (numberIndex == 3) {
            console.log(98)
            if (res.data[2].status === 1) {
                $("#getFuzifu").unbind("click")
                setTimeout(() => {
                    $('#getFuzifu img').attr('src', 'https://img.ameimeika.com/h5_images/fortunebag/yilingqu.png');
                }, 15000)
            }
        } else if (numberIndex == 2) {
            if (res.data[1].share_number > 0 && res.data[1].share_number <= 3) {
                setTimeout(() => {
                    numberTwo = res.data[1].share_number;
                    $('.kaContent').html("(" + numberTwo + "/" + "3" + ")")
                }, 15000)
            }
            if (res.data[1].status == 1) {
                setTimeout(() => {
                    $('#getKazifu img').attr('src', 'https://img.ameimeika.com/h5_images/fortunebag/yilingqu.png');
                    $("#getKazifu").unbind("click")
                }, 15000)

            }
        } else if (numberIndex == 1) {
            if (res.data[0].status == 1) {
                var name = res.data[0].beautify;
                var phone = res.data[0].mobile;
                $('.name').html('<input type="text" id="name" disabled="disabled">')
                $('#name').val(name)
                $('.phone').html('<input type="tel" id="phone" disabled="disabled" >' + '<button id="btn">' + '</button>')
                $('#phone').val(phone)
                $('.active-box .right img').attr('src', 'https://img.ameimeika.com/h5_images/fortunebag/yilingqu.png');
                $('#btn').click(function () {
                    $('html,body').animate({
                        scrollTop: $('.active').offset().top
                    }, 800);
                })
                $("#getBtn").unbind("click")
            }
        }
        if (res.data[3].status == 1) {
            number = 5
        }
        if (res.data[0].status == 1 && res.data[1].status == 1 && res.data[2].status == 1 && res.data[3].status == 1) {
            $('#plusBox').removeClass('hide')
        }

    })
}
// 袋字福
function getDai(id) {
    console.log(number)
    if (number == 5) {
        return
    } else {
        ajax('/api/act/new_year/four_step', {
            project_id: id
        }, function success(res) {
            var numberIndex = 4
            getFu(numberIndex)
        })
    }


}
// 福字福
function getFuzifu() {
    ajax('/api/act/new_year/three_step', {}, function success(res) {
        console.log(res)
        var numberIndex = 3
        getFu(numberIndex)

    })
}
// 咖字福
function getKazifu() {
    ajax('/api/act/new_year/two_step', {}, function success(res) {
        // console.log(res)
        var numberIndex = 2
        getFu(numberIndex)
    })
}
// 商品流跳转详情

function toDetail(id) {

    if ((noshare == 'true' && env != 1) || (type == '2' && model == '2' && env != 1) || (type == '2' && model == '3' && env != 1)) {
        window.location.href = 'http://url.cn/5TKxNtL'
        return
    }
    if (env == 1) {
        //wx
        if (token) {
            getDai(id)
        }
        wx.miniProgram.navigateTo({
            url: "/pages/project_detail/main?id=" + id
        });
    } else if (env == 2) {
        //Android
        if (token) {
            getDai(id)
        }
        var jsonData = {
            "id": id
        };
        window.WebViewJsController.jsGetData(4, 4, JSON.stringify(jsonData), null);
    } else if (env == 3) {
        //IOS
        if (token) {
            getDai(id)
        }
        window.webkit.messageHandlers.navigate.postMessage({
            "type": 3,
            "id": id
        });
    }
}


// 商品流
function getGoods() {
    if (isBottom) {
        return false;
    }
    ajax('/api/v4_2/project/project_search', {
        page: page,
        pageSize: pageSize,
        is_dashboard: 0,
        lat: 0,
        lng: 0,
        sales_sort: sales_sort,
        collect_sort: collect_sort,
        price_sort: price_sort,
        keyword: keyword
    }, function success(res) {
        if (res.status_code == 0) {
            var data = res.data.data;
            if (page == 1 && data.length > 0) {
                goodslist = data;
            } else if (page > 1 && data.length > 0) {
                data.map(function (item) {
                    return goodslist.push(item);
                })
            } else if (page > 1 && data.length == 0) {
                isBottom = true;
                // $("#daodi").show();
                showMsg('已经到最底下了');
            }
            render(goodslist);
        } else {
            showMsg(res.message);
        }
    });
}
// 商品流分页
function isDown(options) {
    var offset, callback;
    offset = options.offset ? options.offset : 20;
    callback = options.callback ? options.callback : null;
    $(document).on('scroll', function () {
        var top = parseInt($(document).scrollTop());
        top >= ($(document).height() - $(window).height() - offset) ? callback && callback() : false
    })
}
// 商品流数据渲染
function render(arr) {
    var array = arr;
    if (array) {
        var html = "";
        array.forEach(function (item, i) {
            html += '<div class="mall" onclick="toDetail(' + item.id + ')">' + '<img  src="' + imgUrl + item.image + '" class="mallImg">' + '<div class="fonts"><div class="top"><h2>' + item.name + '</h2><div class="top_cont"><p>' + item.hospitals_name + '</p><div class="address">' + item.address + '</div></div></div><div class="plus_title">' + item.plus_title + '</div><div class="bottom"><div class="price">优惠价<p>¥<span>' + item.discounts + '</span>起</p></div><div class="person_num">' + item.appointment_peoples + '人已预约</div></div></div>' + '</div>';
        });
        $("#maillList").html(html).height('100%');
    }
}
getGoods()



// 数据统计
function tongji(action) {
    ajax('/api/act/new_year/tongji', {
        action: action
    }, function success(res) {
        console.log(res)
    })

}

// 判断环境
function getEnv() {
    var u = window.navigator.userAgent;
    if (/MicroMessenger/i.test(u)) {
        // 微信
        wx.miniProgram.getEnv(function (res) {
            if (res.miniprogram) {
                env = 1;
            }
        });
    } else {
        // app环境
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if (isAndroid) {
            env = 2;
        }
        if (isIOS) {
            env = 3;
        }
    }
}
// 分享功能
$(function () {
    $('#addShare').on('click', '', function () {
        if ((noshare == 'true' && env != 1) || (type == '2' && model == '2' && env != 1) || (type == '2' && model == '3' && env != 1)) {
            window.location.href = 'http://url.cn/5TKxNtL'
            return
        }
        if (env == 1) { //微信
            $("#sharing").removeClass('hide');
            tongji('share_click')
        } else if (env == 2) { //Android
            var jsonData = {
                wechat_path: '/pages/entry/main?t=30&tg=0&sid=0',
                wechatcicle_url: 'https://h5.ameimeika.com/Fortunebag/index.html',
                title: '0元领轻医美项目~年前变美大冲刺~',
                descripe: '',
                share_image: 'https://img.ameimeika.com/h5_images/fortunebag/shap.png'
            }
            window.WebViewJsController.jsGetData(7, 18, JSON.stringify(jsonData), null);
            tongji('share_click')
        } else if (env == 3) { //IOS
            window.webkit.messageHandlers.minishare.postMessage({
                url: 'https://h5.ameimeika.com/Fortunebag/index.html',
                path: '/pages/entry/main?t=30&tg=0&sid=0',
                title: '0元领轻医美项目~年前变美大冲刺~',
                desc: '',
                image: 'https://img.ameimeika.com/h5_images/fortunebag/shap.png',
                type: '3'
            })
            tongji('share_click	')
        }
    })
    //取消分享

    $('#sharing').click(function () {
        $("#sharing").addClass('hide');
    })

    // 福字福分享到朋友圈
    $('#getFuzifu').click(function () {
        if ((noshare == 'true' && env != 1) || (type == '2' && model == '2' && env != 1) || (type == '2' && model == '3' && env != 1)) {
            window.location.href = 'http://url.cn/5TKxNtL'
            return
        }
        if (env == 1) { //微信
            $("#sharing").removeClass('hide');
            if (token) {
                getFuzifu()
            }
        } else if (env == 2) { //Android
            var jsonData = {
                wechat_path: '/pages/advertisement/main?url=' + encodeURIComponent(pageUrl),
                wechatcicle_url: 'https://h5.ameimeika.com/Fortunebag/index.html?noshare=true',
                title: '0元领轻医美项目~年前变美大冲刺~',
                descripe: '',
                share_image: 'https://img.ameimeika.com/h5_images/fortunebag/shap.png'
            }
            window.WebViewJsController.jsGetData(7, 18, JSON.stringify(jsonData), null);
            if (token) {
                getFuzifu()
            }
        } else if (env == 3) { //IOS
            window.webkit.messageHandlers.minishare.postMessage({
                url: 'https://h5.ameimeika.com/Fortunebag/index.html?noshare=true',
                path: '/pages/advertisement/main?url=' + encodeURIComponent(pageUrl),
                title: '0元领轻医美项目~年前变美大冲刺~',
                desc: '',
                image: 'https://img.ameimeika.com/h5_images/fortunebag/shap.png',
                type: '3'
            })
            if (token) {
                getFuzifu()
            }
        }
    })

    // 咖字福分享好友
    $('#getKazifu').click(function () {
        if ((noshare == 'true' && env != 1) || (type == '2' && model == '2' && env != 1) || (type == '2' && model == '3' && env != 1)) {
            window.location.href = 'http://url.cn/5TKxNtL'
            return
        }
        if (env == 1) { //微信
            $("#sharing").removeClass('hide');
            if (token) {
                getKazifu()
            }
        } else if (env == 2) { //Android
            var jsonData = {
                wechat_path: '/pages/entry/main?t=30&tg=0&sid=0',
                wechatcicle_url: 'https://h5.ameimeika.com/Fortunebag/index.html',
                title: '0元领轻医美项目~年前变美大冲刺~',
                descripe: '',
                share_image: 'https://img.ameimeika.com/h5_images/fortunebag/shap.png'
            }
            window.WebViewJsController.jsGetData(7, 18, JSON.stringify(jsonData), null);
            if (token) {
                getKazifu()
            }
        } else if (env == 3) { //IOS
            window.webkit.messageHandlers.minishare.postMessage({
                url: 'https://h5.ameimeika.com/Fortunebag/index.html',
                path: '/pages/entry/main?t=30&tg=0&sid=0',
                title: '0元领轻医美项目~年前变美大冲刺~',
                desc: '',
                image: 'https://img.ameimeika.com/h5_images/fortunebag/shap.png',
                type: '3'
            })
            if (token) {
                getKazifu()
            }
        }
    })

    // 解决ios键盘抬起事件
    var timer = ""
    $("input").focus(function () {
        clearTimeout(timer);
    })
    $("input").focusout(function () {
        timer = setTimeout(() => {
            window.scrollTo(0, 0);
            // 间隔设为10，减少页面失去焦点定时器的突兀感，
        }, 10);
    })
    // 校验手机号
    $("#phone").blur(function () {
        var myreg = /^1\d{10}$/;
        if ($(this).val()) {
            if (!myreg.test($(this).val())) {
                showMsg('请输入正确手机号');
            }
        }
    });
    $('input').on('input propertychange', function () {
        var getCon = $(this).val().replace(/\s+/g, "")
        console.log(getCon)
        if ($(this).val().length >= 20) {
            showMsg('最多输入20个字符哦');
        }
    });
})


//小程序分享
wx.miniProgram.postMessage({
    data: {
        title: '0元领轻医美项目~年前变美大冲刺~',
        desc: '',
        imageUrl: "https://img.ameimeika.com/h5_images/fortunebag/shap.png",
        path: '/pages/entry/main?t=30&tg=0&sid=0'
    }
});

//ajax请求封装
function ajax(url, data, callback) {
    $.ajax({
        type: 'post',
        url: baseUrl + url,
        data: data || {},
        dataType: 'json',
        headers: {
            Authorization: "Bearer " + token
        },
        success: callback,
        error: function error(err) {
            // showMsg('网络错误，请稍后重试');
        }
    });
}

// 消息提示
function showMsg(msg) {
    $("#tip").removeClass('hide');
    $("#tipMsg").html(msg);
    setTimeout(function () {
        $("#tip").addClass('hide');
        $("#tipMsg").html('');
    }, 1000);
}